package top.lunarye.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import top.lunarye.modules.staff.entity.Role;
import top.lunarye.modules.staff.entity.RoleEnum;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @description:
 * @author: lunar
 * @since: 2021-07-20
 */
public class NumberEnumTypeHandler extends BaseTypeHandler<RoleEnum> {
    private Class<RoleEnum> type;

    public NumberEnumTypeHandler(){};

    public NumberEnumTypeHandler(Class<RoleEnum> type) {
        if (type == null) throw new IllegalArgumentException("Type argument cannot be null");
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, RoleEnum parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setInt(i, parameter.getId());
    }

    @Override
    public RoleEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return RoleEnum.getRoleEnum(rs.getInt(columnName));
    }

    @Override
    public RoleEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return RoleEnum.getRoleEnum(rs.getInt(columnIndex));
    }

    @Override
    public RoleEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return RoleEnum.getRoleEnum(cs.getInt(columnIndex));
    }

//    private RoleEnum getEnum(Integer val) {
//        Class<RoleEnum> roleClass = RoleEnum.class;
//        RoleEnum[] roles = roleClass.getEnumConstants();
//
//        for (RoleEnum role: roles) {
//            if (role.getId().equals(val)) {
//                return role;
//            }
//        }
//        return null;
//    }
}
